<template>
  <div>
    <van-button class="m-add" type="primary" block @click="handleClerk(null)">添加人员</van-button>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多数据了"
      @load="onLoad"
    >
      <van-swipe-cell v-for="item in list" :key="item.id" class="m-s-cell-boss">
        <template #left>
          <van-button
            square
            type="info"
            text="变更信息"
            @click="handleClerk(item)"
          />
        </template>
        <van-cell
          :border="false"
          :title="item.cname"
          style="text-align: center"
        >
          <van-tag v-if="item.status === 0" type="warning">大师点评中</van-tag>
          <van-tag v-else type="success">终极报告</van-tag>
        </van-cell>
        <template #right>
          <van-button
            square
            type="info"
            :url="'/#/mobile/clerk/' + item.id + '?ccode='+ item.ccode"
          >个人主页</van-button>
          <van-button
            v-if="item.status === 1"
            square
            type="primary"
            :url="'/customreport/m' + item.id + '.pdf'"
          >熠学报告</van-button>
        </template>
      </van-swipe-cell>
    </van-list>
    <van-popup
      v-model="show"
      closeable
      round
      position="bottom"
      :style="{ height: '96%' }"
    >
      <van-form @submit="onSubmit">
        <van-field
          v-model="clerkObj.cname"
          name="姓名"
          label="姓名"
          placeholder="姓名"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />
        <van-field label="性别">
          <template #extra>
            <van-radio-group
              v-model="clerkObj.sex"
              direction="horizontal"
              class="m-salon-field"
            >
              <van-radio :name="0">男</van-radio>
              <van-radio :name="1">女</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-datetime-picker
          v-model="currentDate"
          cancel-button-text=" "
          type="year-month"
          title="选择年月"
          :min-date="minDate"
          :max-date="maxDate"
          :formatter="formatter"
          @confirm="changeYear"
        />
        <calendar
          ref="calendar"
          class="m-boss-calendar"
          width="100%"
          style="line-height: 20px"
          :show-week-day="false"
          :show-title="false"
          :show-festival="false"
          :show-term="false"
          @date-click="wnlclick($event)"
        />

        <van-field
          v-model="clerkObj.solar"
          name="阳历"
          label="阳历"
          placeholder="阳历"
          :rules="[{ required: true, message: '请选择阳历' }]"
        />
        <van-field
          v-model="clerkObj.lunar"
          name="阴历"
          label="阴历"
          placeholder="阴历"
          :rules="[{ required: true, message: '请选择阴历' }]"
        />
        <van-field label="出生时间">
          <template #extra>
            <van-dropdown-menu active-color="#1989fa" class="m-salon-field">
              <van-dropdown-item v-model="birthTime" :options="options" />
            </van-dropdown-menu>
          </template>
        </van-field>
        <van-field
          v-model="clerkObj.city"
          name="出生城市"
          label="出生城市"
          placeholder="出生城市"
        />
        <van-field
          v-model="clerkObj.tel"
          name="电话"
          label="电话"
          placeholder="电话"
        />
        <van-field label="店内职务">
          <template #extra>
            <van-radio-group v-model="clerkObj.post" class="m-salon-field">
              <van-radio name="老板">老板</van-radio>
              <van-radio name="店长">店长</van-radio>
              <van-radio name="负责人（经理）">负责人（经理）</van-radio>
              <van-radio name="店员">店员</van-radio>
              <van-radio name="客户">客户</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit">提交</van-button>
        </div>
      </van-form>
    </van-popup>
  </div>
</template>
<script>
import 'vue-lunar-calendar-pro/dist/calendar.css'
import Calendar from 'vue-lunar-calendar-pro'
import Button from 'vant/lib/button'
import List from 'vant/lib/list'
import CellGroup from 'vant/lib/cell-group'
import Cell from 'vant/lib/cell'
import SwipeCell from 'vant/lib/swipe-cell'
import Tag from 'vant/lib/tag'
import Popup from 'vant/lib/popup'
import Form from 'vant/lib/form'
import Field from 'vant/lib/field'
import RadioGroup from 'vant/lib/radio-group'
import Radio from 'vant/lib/radio'
import DatetimePicker from 'vant/lib/datetime-picker'
import Divider from 'vant/lib/divider'
import DropdownMenu from 'vant/lib/dropdown-menu'
import DropdownItem from 'vant/lib/dropdown-item'
import Notify from 'vant/lib/notify'
import 'vant/lib/notify/style'
import 'vant/lib/dropdown-menu/style'
import 'vant/lib/dropdown-item/style'
import 'vant/lib/divider/style'
import 'vant/lib/datetime-picker/style'
import 'vant/lib/radio-group/style'
import 'vant/lib/radio/style'
import 'vant/lib/form/style'
import 'vant/lib/field/style'
import 'vant/lib/popup/style'
import 'vant/lib/button/style'
import 'vant/lib/list/style'
import 'vant/lib/cell/style'
import 'vant/lib/cell-group/style'
import 'vant/lib/tag/style'
import 'vant/lib/swipe-cell/style'
import { mapGetters } from 'vuex'
import { getShopClerks, addClerk, editClerk } from '@/api/txs'

export default {
  components: {
    [Notify.name]: Notify,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Divider.name]: Divider,
    [DatetimePicker.name]: DatetimePicker,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Form.name]: Form,
    [Field.name]: Field,
    [Popup.name]: Popup,
    [Button.name]: Button,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Tag.name]: Tag,
    [SwipeCell.name]: SwipeCell,
    [List.name]: List,
    Calendar
  },
  props: {
    salon: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
      birthTime: '',
      options: [
        { text: '时间未知', value: '' },
        { text: '23--01【子时】夜半', value: '23' },
        { text: '01--03【丑时】鸡鸣', value: '01' },
        { text: '03--05【寅时】平旦', value: '03' },
        { text: '05--07【卯时】日出', value: '05' },
        { text: '07--09【辰时】食时', value: '07' },
        { text: '09--11【巳时】隅中', value: '09' },
        { text: '11--13【午时】日中', value: '11' },
        { text: '13--15【未时】日昳', value: '13' },
        { text: '15--17【申时】哺时', value: '15' },
        { text: '17--19【酉时】日入', value: '17' },
        { text: '19--21【戌时】黄昏', value: '19' },
        { text: '21--23【亥时】人定', value: '21' }
      ],
      minDate: new Date(1925, 0, 1),
      maxDate: new Date(2025, 0, 1),
      currentDate: new Date(2000, 0, 10),
      clerkObj: {
        id: undefined,
        sid: undefined,
        pic: '',
        status: 0,
        sex: 1,
        tel: '',
        post: '店员',
        solar: '',
        lunar: '',
        btime: '',
        city: '',
        ccode: '',
        cname: '',
        gzn: '',
        gzy: '',
        gzr: ''
      },
      show: false,
      list: [],
      loading: false,
      finished: false
    }
  },
  computed: {
    ...mapGetters(['openId', 'name'])
  },
  // created () {
  //   this.fetchData()
  // },
  methods: {
    formatter (type, val) {
      if (type === 'year') {
        return `${val}年`
      } else if (type === 'month') {
        return `${val}月`
      }
      return val
    },
    changeYear (val) {
      this.$refs.calendar.render(val.getFullYear(), val.getMonth() + 1)
    },
    wnlclick (e) {
      this.clerkObj.solar = e.year + '年' + e.month + '月' + e.day + '日'
      this.clerkObj.lunar = e.gzYear + '年' + e.lunarMonth + e.lunar
      this.clerkObj.gzn = e.gzYear
      this.clerkObj.gzy = e.gzMonth
      this.clerkObj.gzr = e.gzDay
    },
    onLoad () {
      this.loading = false
      getShopClerks(this.openId).then(res => {
        this.list = res.data.data
        this.finished = true
      })

      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // setTimeout(() => {
      //   for (let i = 0; i < 10; i++) {
      //     this.list.push(this.list.length + 1)
      //   }
      //   // 加载状态结束
      //   this.loading = false
      //   // 数据全部加载完成
      //   if (this.list.length >= 40) {
      //     this.finished = true
      //   }
      // }, 1000)
    },
    onSubmit () {
      // birthTime 换给 btime
      const tempData = Object.assign({}, this.clerkObj)
      if (this.birthTime && this.birthTime.length > 0) {
        console.log(11111, this.birthTime)
        if (tempData.btime && tempData.btime.split(':')[0] === this.birthTime) {
          console.log('dont change')
        } else {
          tempData.btime = this.birthTime + ':00'
        }
      } else {
        tempData.btime = ''
      }

      if (this.clerkObj.id) {
        editClerk(tempData).then((res) => {
          const d = res.data.data
          const index = this.list.findIndex(v => v.id === this.clerkObj.id)
          this.list.splice(index, 1, d)
          this.show = false
          Notify({ type: 'success', message: '变更成功' })
        }).catch((err) => {
          console.log(err)
          Notify({ type: 'danger', message: '变更失败' })
        })
      } else {
        if (tempData.post === '老板') {
          tempData.ccode = this.salon.code + '-a'
        } else if (tempData.post === '客户') {
          tempData.ccode = this.salon.code + '-c'
        } else {
          tempData.ccode = this.salon.code + '-b'
        }
        tempData.creator = this.name
        tempData.checked = 0
        addClerk(tempData)
          .then(res => {
            const d = res.data.data
            this.list.unshift(d)
            // console.log(d)
            this.show = false
            Notify({ type: 'success', message: '添加成功' })
          })
          .catch(_ => Notify({ type: 'danger', message: '添加失败' }))
      }
    },
    handleClerk (clerk) {
      if (clerk) {
        this.clerkObj = Object.assign({}, clerk)
        this.birthTime = this.getBirthTime(this.clerkObj.btime)
      } else {
        this.clerkObj = this.$options.data().clerkObj
        this.clerkObj.sid = this.salon.id
        this.birthTime = ''
      }
      this.show = true
    },
    getBirthTime (val) {
      if (val && val.length > 0) {
        const bt = val.split(':')[0]
        switch (bt) {
          case '23':
          case '00':
            return '23'
          case '01':
          case '02':
            return '01'
          case '03':
          case '04':
            return '03'
          case '05':
          case '06':
            return '05'
          case '07':
          case '08':
            return '07'
          case '09':
          case '10':
            return '09'
          case '11':
          case '12':
            return '11'
          case '13':
          case '14':
            return '13'
          case '15':
          case '16':
            return '15'
          case '17':
          case '18':
            return '17'
          case '19':
          case '20':
            return '19'
          case '21':
          case '22':
            return '21'
          default:
            return ''
        }
      }
      return ''
    }
  }
}
</script>
<style lang="scss">
.m-s-cell-boss {
  .van-swipe-cell__left {
    top: -20px;
  }
  .van-swipe-cell__right {
    top: -20px;
  }
}
.m-boss-calendar.showWeek.calendar-pro > div > table {
  thead {
    display: none;
  }
  td {
    .info-lunar {
      bottom: 0;
      right: 0;
      font-size: 20px;
    }
  }
}
</style>
<style lang="scss" scoped>
.m-add {
  margin-bottom: 10px;
}
.m-div {
  font-size: 30px;
  font-weight: bold;
}
.m-p {
  font-size: 24px;
}
.m-salon-field {
  margin-right: 200px;
}
</style>
